/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.math.BigDecimal;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import model.Customer;
import model.Order;
import model.OrderLine;

/**
 *
 * @author jhon
 */
public class Queries {
    
    
    
    
    public Customer createCustomer(EntityManagerFactory emf) {
        EntityManager em = emf.createEntityManager();
        Customer customer = new Customer();
        customer.setName("AMCE-" + System.currentTimeMillis());
        em.getTransaction().begin();
        em.persist(customer);
        em.getTransaction().commit();
        em.close();
        return customer;
    }
    
    public boolean searchMonster(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Query q = em.createNativeQuery("select * from CUSTOMER as c, ORDERLINE as o where c.id between 3 and 107;");
        em.getTransaction().begin();
        q.getResultList();
        em.getTransaction().commit();
        em.close();
        return true;
    }
    
    public boolean searchMonsterNativeQuery(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Query q = em.createNamedQuery("searchMonster");
        em.getTransaction().begin();
        q.getResultList();
        em.getTransaction().commit();
        em.close();
        return true;
    }

    public Order placeOrder(Customer customer, EntityManagerFactory emf) {
        EntityManager em = emf.createEntityManager();
        customer = em.find(customer.getClass(), customer.getId());
        Order order = new Order();
        order.setDescription("Order-" + System.currentTimeMillis());
        em.getTransaction().begin();
        em.persist(order);
        em.getTransaction().commit();
        
        order = em.find(Order.class, order.getId());
        
        for (int index = 0; index < 2; index++) {
            OrderLine orderline = new OrderLine("item-" + index, new BigDecimal(index * 100));
            orderline.setOrderObj(order);
            em.getTransaction().begin();
            em.persist(orderline);
            em.getTransaction().commit();
        }
        
        em.close();
        return order;
    }
    
        public boolean findOrder(EntityManagerFactory emf) {
        EntityManager em = emf.createEntityManager();
        searchMonster(emf);
        return true;
    }
    
    
}
